package com.qk.management.web.interceptor;


import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @author 李智勇
 * @data 2025/10/11 15:51
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    // 请求头中名字叫token
    private static final String TOKEN_HEADER_NAME = "token";

    /**
     *  拦截请求，在到达控制器之前执行
     *  登录校验
     * @param request 请求
     * @param response 响应
     * @param handler 处理器
     * @return  boolean ture 放行 false 拦截
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //1. 获取请求头中的token
        String token = request.getHeader(TOKEN_HEADER_NAME);
        //2. 判断token是否为空 java 8 ->  Optional  强制判空容器 ！ 思想：要求定义方法时候返回值定义成 Optional
        if (Objects.isNull(token)){
            log.info("请求头中没有token");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        // 3. 解析token
        try {
            Claims claims = JwtUtils.parseToken(token);
            log.info("-----token验证成功-----");
            String username = claims.get("username", String.class);
            log.info("-----用户信息是：{}-----", username);
            Integer id = claims.get("id",Integer.class);
            log.info("-----用户id是：{}-----", id);
            // 将用户id存入当前线程中ThreadLocal
            CurrentUserContextHolders.set(id);
            return true;
        }catch (Exception e){
            log.error("-----token验证失败-----", e);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.remove();
    }
}
